/*
    Copyright 2010 Barnet Wagman

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

package com.norbl.util;

/** A 'database element' represents the data in one 'row' of a database (aka
 *  one item in sdb).  Why not just use a <tt>PropertyList</tt>?
 *  Creating objects with specific fields is
 *  less prone to (human) error than creating a more general entity like a
 *  <tt>PropertyList</tt>.  <tt>PropertyList</tt>s can be converted to 
 *  <tt>DbEl</tt>s and vice versa.<p>
 * 
 *  Note that although <tt>DbEl</tt> is used to handle data stored in sdb,
 *  it does not support multiple values per attribute.
 * 
 * @author Barnet Wagman
 */
abstract public class DbEl {
    
    abstract public DbElField[] getRelevantFields();

    abstract public DbElField[] getDisplayFields();

    abstract public Object getPropertyValue(Property p);

    public DbEl() {}

    public DbEl(PropertyList pl,boolean allowMissingFields)
        throws MissingFieldException {
        try {
            DbElField[] flds = getRelevantFields();
            for (DbElField f : flds ) {
                Property p = pl.getProperty(f.name);
                if ( p != null ) {
                    f.field.set(this,getPropertyValue(p));
                }
                else if ( allowMissingFields )
                    f.field.set(this,null);
                else throw new MissingFieldException("The PropertyList " +
                        " lacks " + f.name);
            }
        }
        catch(Exception x) {
            if ( x instanceof MissingFieldException)
                throw ((MissingFieldException) x);
            else throw new RuntimeException(x);
        }
    }

    public PropertyList toPropertyList() {
      
        PropertyList pl = new PropertyList();

        DbElField[] flds = getRelevantFields();

        for ( DbElField f : flds ) {
            pl.add(new Property(f.name,f.getVal()));
        }

        return(pl);
    }

    
}
